﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace JWT.Controllers
{
    public class AuthController : Controller
    {
        [HttpPost]
        public string GetToken(string userName, string password)
        {
            // 验证用户名和密码逻辑
            if (userName == "admin" && password == "password")
            {
                return  GenerateToken(userName);
            }

            return "Login failed";
        }

        [Authorize]
        [HttpGet]
        public string TestAuth() 
        {
            return "Access JWT Auth Success!";
        }

        [Authorize(Policy = "Admin")]
        [HttpGet]
        public string TestAuthAdmin()
        {
            return "Access JWT Admin Auth Success!";
        }

        /// <summary>
        /// 生成Token
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        private string GenerateToken(string userName)
        {
            List<Claim> claims = new()
            {
                //new Claim(ClaimTypes.Name,userName),
                //放开这段代码    TestAuthAdmin请求会正常返回数据
                new Claim(ClaimTypes.Role,"Admin")
            };

            var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("KKqUZx15DF2y01rPNaPOYr4doES59Mbu"));
            var expires = DateTime.Now.AddDays(30);
            var token = new JwtSecurityToken(
                issuer: "MDCServer",
                audience: "MDCClient",
                claims: claims,
                notBefore: DateTime.Now,
                expires: expires,
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
